MessageHandler.process   C
last analyzed

Complexity

Conditions 10

Size

Total Lines 44
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 39
dl 0
loc 44
rs 5.9999
c 0
b 0
f 0
cc 10

How to fix   Complexity   

Complexity

Complex classes like MessageHandler.process often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import {chat_v1 as chatV1} from '@googleapis/chat';
2
import BaseHandler from './BaseHandler';
3
import {splitMessage} from '../helpers/utils';
4
import PollCard from '../cards/PollCard';
5
import {generateHelpText, helperButtonCard} from '../helpers/helper';
6
7
export default class MessageHandler extends BaseHandler {
8
  process(): chatV1.Schema$Message {
9
    const argumentText = this.event.message?.argumentText?.trim() ?? '';
10
11
    const helpResponse = {
12
      thread: this.event.message!.thread,
13
      actionResponse: {
14
        type: 'NEW_MESSAGE',
15
      },
16
      text: '',
17
      cardsV2: [helperButtonCard],
18
    };
19
    const isPrivate = this.event.space?.type === 'DM';
20
21
    switch (argumentText) {
22
      case 'help':
23
        helpResponse.text = generateHelpText(isPrivate);
24
        return helpResponse;
25
      case 'test dyas':
26
        helpResponse.text = 'Hello <https://github.com/dyaskur/google-chat-poll|google-chat-poll>';
27
        return helpResponse;
28
      default:
29
        const choices = splitMessage(argumentText);
30
        const annotation = this.getAnnotationByType('USER_MENTION');
31
        if (annotation && choices.length > 2) {
32
          const pollCard = new PollCard({
33
            choiceCreator: undefined,
34
            topic: choices.shift() ?? '',
35
            author: this.event.user,
36
            choices: choices,
37
            votes: {},
38
            anon: false,
39
            optionable: true,
40
          }, this.getUserTimezone());
41
          const message = pollCard.createMessage();
42
          return {
43
            thread: this.event.message!.thread,
44
            actionResponse: {
45
              type: 'NEW_MESSAGE',
46
            },
47
            ...message,
48
          };
49
        }
50
        helpResponse.text = generateHelpText(isPrivate);
51
        return helpResponse;
52
    }
53
  }
54
}
55